import React, { useState, useEffect, useRef } from 'react';
import Modal from './Modal';
import { GameSettings, ChatMessage } from '../types';
import { getModelAndChannel, refineRulebook } from '../services/apiService';
import LoadingSpinner from './LoadingSpinner';
import MarkdownRenderer from './MarkdownRenderer';

interface RulebookTuningModalProps {
  isOpen: boolean;
  onClose: () => void;
  initialRules: string;
  initialChatHistory: ChatMessage[];
  gameName: string;
  backgroundStory: string;
  settings: GameSettings;
  showToast: (message: string, type?: 'success' | 'error') => void;
  onFinalize: (newRules: string, newHistory: ChatMessage[]) => void;
}

const ArrowsPointingOutIcon: React.FC<React.SVGProps<SVGSVGElement>> = (props) => (
  <svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" strokeWidth={1.5} stroke="currentColor" {...props}>
    <path strokeLinecap="round" strokeLinejoin="round" d="M3.75 3.75v4.5m0-4.5h4.5m-4.5 0L9 9M3.75 20.25v-4.5m0 4.5h4.5m-4.5 0L9 15M20.25 3.75v4.5m0-4.5h-4.5m4.5 0L15 9m5.25 11.25v-4.5m0 4.5h-4.5m4.5 0L15 15" />
  </svg>
);

const ArrowsPointingInIcon: React.FC<React.SVGProps<SVGSVGElement>> = (props) => (
  <svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" strokeWidth={1.5} stroke="currentColor" {...props}>
    <path strokeLinecap="round" strokeLinejoin="round" d="M9 9V4.5M9 9H4.5M9 9L3.75 3.75M9 15v4.5M9 15H4.5M9 15l-5.25 5.25M15 9V4.5M15 9h4.5M15 9l5.25-5.25M15 15v4.5M15 15h4.5M15 15l5.25 5.25" />
  </svg>
);


const RulebookTuningModal: React.FC<RulebookTuningModalProps> = ({
  isOpen, onClose, initialRules, initialChatHistory, gameName, backgroundStory, settings, showToast, onFinalize,
}) => {
  const [currentRulesText, setCurrentRulesText] = useState(initialRules);
  const [chatHistory, setChatHistory] = useState<ChatMessage[]>(initialChatHistory);
  const [userInput, setUserInput] = useState('');
  const [isLoading, setIsLoading] = useState(false);
  const [isMaximized, setIsMaximized] = useState(false);
  const chatHistoryRef = useRef<HTMLDivElement>(null);

  useEffect(() => {
    setCurrentRulesText(initialRules);
    if (initialChatHistory.length === 0) {
        setChatHistory([{ role: 'assistant', content: '欢迎来到规则书工作台！请在下方输入您的编写或修改要求。', generatedPrompt: initialRules }]);
    } else {
        setChatHistory(initialChatHistory);
    }
  }, [initialRules, initialChatHistory]);

  useEffect(() => {
    if (chatHistoryRef.current) {
      chatHistoryRef.current.scrollTop = chatHistoryRef.current.scrollHeight;
    }
  }, [chatHistory]);

  const handleSendMessage = async () => {
    if (!userInput.trim() || isLoading || !settings) return;

    const { model, channel } = getModelAndChannel(settings, settings.defaultTextModelId);
    if (!model || !channel) {
      showToast("未找到有效的默认文本模型或API渠道配置。", "error");
      return;
    }

    const userMessageContent = userInput;
    const newUserMessage: ChatMessage = { role: 'user', content: userMessageContent };

    setChatHistory(prev => [...prev, newUserMessage]);
    setUserInput('');
    setIsLoading(true);

    try {
      const refined = await refineRulebook(
        gameName, 
        backgroundStory, 
        currentRulesText,
        userMessageContent, 
        channel, 
        model, 
        settings.corsProxyUrl, 
        settings.requestTimeout
      );
      
      const newAssistantMessage: ChatMessage = { 
        role: 'assistant', 
        content: '我已经根据您的要求更新了规则书。', 
        generatedPrompt: refined 
      };

      setCurrentRulesText(refined);
      setChatHistory(prev => [...prev, newAssistantMessage]);
      showToast("AI已更新规则书！", "success");

    } catch (error) {
      const errorMessage = error instanceof Error ? error.message : "未知错误";
      showToast(`优化失败: ${errorMessage}`, "error");
      
      const errorAssistantMessage: ChatMessage = { 
        role: 'assistant', 
        content: `抱歉，在处理您的请求时遇到了一个问题: ${errorMessage}` 
      };
      setChatHistory(prev => [...prev, errorAssistantMessage]);
    } finally {
      setIsLoading(false);
    }
  };

  const handleFinalize = () => {
    onFinalize(currentRulesText, chatHistory);
  };
  
  const handleUseVersion = (rulesText: string) => {
    setCurrentRulesText(rulesText);
    showToast("已应用该历史版本。", "success");
  }
  
  if (!isOpen) return null;

  return (
    <div className="fixed inset-0 bg-black bg-opacity-75 flex items-center justify-center z-50 p-4">
      <div className={`bg-gray-800 rounded-lg shadow-xl flex flex-col transition-all duration-300 ease-in-out ${isMaximized ? 'w-[95vw] h-[95vh]' : 'w-full max-w-6xl'}`}>
        <div className="flex justify-between items-center p-4 border-b border-gray-700">
          <h3 className="text-xl font-semibold text-gray-100">AI规则书工作台</h3>
           <div className="flex items-center space-x-4">
              <button onClick={() => setIsMaximized(!isMaximized)} className="text-gray-400 hover:text-gray-200 transition-colors" title={isMaximized ? "还原" : "最大化"}>
                  {isMaximized ? <ArrowsPointingInIcon className="w-5 h-5" /> : <ArrowsPointingOutIcon className="w-5 h-5" />}
              </button>
              <button onClick={onClose} className="text-gray-400 hover:text-gray-200 transition-colors" aria-label="关闭弹窗">
                <svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" strokeWidth={1.5} stroke="currentColor" className="w-6 h-6"><path strokeLinecap="round" strokeLinejoin="round" d="M6 18L18 6M6 6l12 12" /></svg>
              </button>
          </div>
        </div>
        <div className={`p-6 overflow-hidden flex-grow ${isMaximized ? 'h-[calc(95vh-130px)]' : 'h-[75vh]'}`}>
            <div className="grid grid-cols-1 md:grid-cols-3 gap-4 h-full">
                {/* Left Panel: Chat */}
                <div className="md:col-span-1 flex flex-col bg-gray-700/50 rounded-lg p-3">
                    <div ref={chatHistoryRef} className="flex-grow overflow-y-auto pr-2 space-y-4">
                       {chatHistory.map((msg, index) => (
                           <div key={index} className={`flex flex-col ${msg.role === 'user' ? 'items-end' : 'items-start'}`}>
                               <div className={`max-w-xs lg:max-w-sm rounded-lg px-3 py-2 text-sm ${msg.role === 'user' ? 'bg-blue-600 text-white' : 'bg-gray-600 text-gray-200'}`}>
                                   <MarkdownRenderer content={msg.content} />
                                   {msg.role === 'assistant' && msg.generatedPrompt && (
                                       <button onClick={() => handleUseVersion(msg.generatedPrompt!)} className="text-xs mt-2 px-2 py-1 bg-sky-700 hover:bg-sky-600 rounded">
                                           采用此版本
                                       </button>
                                   )}
                               </div>
                           </div>
                       ))}
                       {isLoading && <div className="flex justify-center py-2"><LoadingSpinner size="sm" text="AI思考中..." /></div>}
                    </div>
                    <div className="mt-4 flex-shrink-0">
                        <textarea value={userInput} onChange={(e) => setUserInput(e.target.value)} onKeyPress={(e) => { if (e.key === 'Enter' && !e.shiftKey) { e.preventDefault(); handleSendMessage(); } }} placeholder="输入编写或修改指令..." rows={3} className="w-full p-2 bg-gray-600 border border-gray-500 rounded-md shadow-sm focus:ring-2 focus:ring-blue-500 outline-none text-sm resize-none" disabled={isLoading} />
                        <button onClick={handleSendMessage} disabled={isLoading || !userInput.trim()} className="w-full mt-2 px-4 py-2 bg-blue-600 hover:bg-blue-700 text-white font-semibold rounded-md shadow-sm disabled:opacity-50 disabled:cursor-not-allowed">发送</button>
                    </div>
                </div>

                {/* Middle Panel: Rules Editor */}
                <div className="md:col-span-1 flex flex-col">
                    <textarea value={currentRulesText} onChange={(e) => setCurrentRulesText(e.target.value)} className="w-full h-full p-3 bg-gray-900/50 border border-gray-600 rounded-md shadow-sm focus:ring-2 focus:ring-blue-500 outline-none text-gray-200 text-sm font-mono resize-none"></textarea>
                </div>
                
                {/* Right Panel: Context */}
                <div className="md:col-span-1 flex flex-col gap-4 overflow-y-auto pr-2">
                    <div className="bg-gray-700/50 rounded-lg p-3">
                         <h4 className="font-semibold text-gray-300 mb-2 border-b border-gray-600 pb-1">游戏核心设定</h4>
                         <div className="text-xs text-gray-400 space-y-2">
                             <p><strong>名称:</strong> {gameName}</p>
                             <p><strong>背景:</strong> {backgroundStory}</p>
                         </div>
                    </div>
                </div>
            </div>
        </div>
        <div className="p-4 border-t border-gray-700 flex justify-end w-full">
            <button onClick={handleFinalize} className="px-4 py-2 bg-green-600 hover:bg-green-700 text-white rounded-md">确认并使用</button>
        </div>
      </div>
    </div>
  );
};

export default RulebookTuningModal;
